﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace ZBJF.Warranty.Common.Common
{
    public class DataTableToListHelper<T> where T : new()
    {
        public static T ConvertToEntity(DataRow dr)
        {
            T entity = new T();

            foreach (var item in entity.GetType().GetProperties())
            {
                Type type = item.PropertyType;
                //判断type类型是否为泛型，因为nullable是泛型类,
                if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>))
                {
                    var genericTypeDefinition = type.GetGenericTypeDefinition();
                    if (genericTypeDefinition != null && genericTypeDefinition == typeof(Nullable<>))//判断convertsionType是否为nullable泛型类
                    {
                        //如果type为nullable类，声明一个NullableConverter类，该类提供从Nullable类到基础基元类型的转换
                        System.ComponentModel.NullableConverter nullableConverter =
                            new System.ComponentModel.NullableConverter(type);
                        //将type转换为nullable对的基础基元类型
                        type = nullableConverter.UnderlyingType;
                    }
                }
                if (dr.Table.Columns.Contains(item.Name))
                {
                    if (DBNull.Value != dr[item.Name])
                    {
                        item.SetValue(entity, Convert.ChangeType(dr[item.Name], type), null);
                    }
                }

            }
            return entity;
        }

        public static List<T> ConvertToEntityList(DataTable table)
        {
            return (from DataRow row in table.Rows select ConvertToEntity(row)).ToList();
        }
    }
}
